import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.Socket;
import java.util.Scanner;

public class searchThread implements Runnable{
	saperePeer main;
	Search sText;
	Peer peer;
	Socket sock;
	PrintWriter out = null;
	BufferedReader in = null;
	Thread t;

	public searchThread(saperePeer s, Search se, Peer p) {
		t = new Thread(this,"st");
		this.main = s;
		this.sText = se;
		this.peer = p;
		try {
			sock = new Socket(peer.ipAddress, 4443);
			out = new PrintWriter(sock.getOutputStream(), true);
			in = new BufferedReader(
					new InputStreamReader(sock.getInputStream()));
		} catch (IOException e) {
			// TODO Auto-generated catch block
			System.out.println("Connection Error in searchThread");
			e.printStackTrace();
		}
		t.start();
	}

	public void run() {
		// send our search to the superPeer
		out.println(sText.toString() + byteToHex(sText.searchHash));
		// wait for the superPeer to send results back
		String inputLine;
		Scanner s = null;
		String cType = "";
		try {
			while ((inputLine = in.readLine()) != null) {
				// System.out.println(inputLine);
				s = new Scanner(inputLine).useDelimiter("\\s*;\\s*");
				while (s.hasNext()) {
					cType = s.next();
					if (cType.equals("class:aFile")) {
						aFile newF = new aFile();
						newF.name = s.next();
						newF.size = Integer.parseInt(s.next());
						newF.Peer = s.next();
						newF.shortAbstract = s.next();
						newF.setHash(hexToByte(s.next()));
						// add these results to the searchResult list of the peer
						main.addSearchResult(newF);
					}
				}
				if(cType.equals("done"))
				{
					break;
				}
			}
			out.close();
			in.close();
			sock.close();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

	static String byteToHex(byte[] msg) {
		String result = "";
		for (int i = 0; i < msg.length; i++) {
			char highBits, LowBits;
			highBits = (char) ((msg[i] >>> 4) & 0xf);
			LowBits = (char) (msg[i] & 0xf);
			highBits = (char) ((highBits > 9) ? 'A' + (highBits - 10)
					: '0' + highBits);
			LowBits = (char) ((LowBits > 9) ? 'A' + (LowBits - 10)
					: '0' + LowBits);
			result += highBits;
			result += LowBits;
		}
		return result;
	}

	public static byte[] hexToByte(String s) {
		int len = s.length();
		byte[] data = new byte[len / 2];
		for (int i = 0; i < len; i += 2) {
			data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) + Character
					.digit(s.charAt(i + 1), 16));
		}
		return data;
	}
}
